import amara, urllib2, os, time
from brightcontent.util import UrlDispatch

DELICIOUS_ENV_VAR = 'brightcontent.delicious.feed'
DELICIOUS_XSLT_PARSE_EXPRESSION = u'f:parse-xml($bc:%s)'%DELICIOUS_ENV_VAR

class DeliciousMiddleware(object):
    def __init__(self, app, app_conf):
        self.app_conf = app_conf
        self.application = app
        self.m = UrlDispatch(self.urls)
        self.feedfile = self.app_conf['del.icio.us-feed-file']
        self.feedurl = self.app_conf.get('del.icio.us-feed-url')
        feed = urllib2.urlopen(self.feedurl)
        f = open(self.feedfile, 'w+')
        f.write(feed.read())
        f.close()
        print "wrote %s" % self.feedfile

    def update_delicious_feed(self):
        update = False
        if (time.time() - os.path.getmtime(self.feedfile)) > 1800:
            url = self.app_conf.get('del.icio.us-feed-url')
            feed = urllib2.urlopen(self.feedurl)
            f = open(self.feedfile, 'w+')
            f.write(f.read())
            f.close()

    def delicious_links(self, environ, start_response, **kw):
        self.update_delicious_feed()
        doc = amara.parse(self.feedfile)
        result = []
        for item in doc.RDF.item:
            link = '<li><a href="%s">%s</a></li>' % (item.link, item.title)
            result.append(link)
        environ['brightcontent.delicious.feed'] = '<ul>%s</ul>' % '\n'.join(result[0:10])
        environ['brightcontent.delicious.feed.parse'] = DELICIOUS_XSLT_PARSE_EXPRESSION

    def __call__(self, environ, start_response, **kw):
        path_info = environ.get('PATH_INFO', '/')
        if path_info == '': path_info = '/' # FIXME: just a workaround for a paste bug
        func, query_dict = self.m.match(path_info)
        if func:
            func(self, environ, start_response, **query_dict)
        return self.application(environ, start_response)

    urls = (
        (r'/(?P<year>\d{4})/(?P<month>\d{1,2})/(?P<day>\d{1,2})/.*', delicious_links),
        (r'/(?P<year>\d{4})/(?P<month>\d{1,2})/.*', delicious_links),
        (r'/(?P<year>\d{4})/.*', delicious_links),
        (r'/.*', delicious_links)
    )


